package com.project_doctor.controller;

import com.project_doctor.pojo.Role;
import com.project_doctor.pojo.dto.PermissionDTO;
import com.project_doctor.pojo.dto.RoleDTO;
import com.project_doctor.service.PermissionService;
import com.project_doctor.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理控制器
 */
@RestController
@RequestMapping("/role")
@CrossOrigin
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 获取所有角色列表
     * @return 角色列表数据
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getRoles() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<RoleDTO> roles = roleService.getRolesWithPermissions();
            result.put("success", true);
            result.put("data", roles);
            result.put("message", "获取角色列表成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取角色列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 获取所有权限列表（树形结构）
     * @return 权限列表数据
     */
    @GetMapping("/permissions")
    public ResponseEntity<Map<String, Object>> getPermissions() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<PermissionDTO> permissions = permissionService.getPermissionsByGroup();
            result.put("success", true);
            result.put("data", permissions);
            result.put("message", "获取权限列表成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取权限列表失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 根据角色ID获取角色及其权限信息
     * @param roleId 角色ID
     * @return 角色权限数据
     */
    @GetMapping("/{roleId}")
    public ResponseEntity<Map<String, Object>> getRolePermissions(@PathVariable Long roleId) {
        Map<String, Object> result = new HashMap<>();
        try {
            RoleDTO role = roleService.getRoleWithPermissionsById(roleId);
            result.put("success", true);
            result.put("data", role);
            result.put("message", "获取角色权限成功");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取角色权限失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 保存角色信息（新增或更新）
     * @param roleDTO 角色数据传输对象
     * @return 保存结果
     */
    @PostMapping("/save")
    public ResponseEntity<Map<String, Object>> saveRole(@RequestBody RoleDTO roleDTO) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = roleService.saveRoleWithPermissions(roleDTO);
            if (success) {
                result.put("success", true);
                result.put("message", "保存角色成功");
            } else {
                result.put("success", false);
                result.put("message", "保存角色失败");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "保存角色失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 更新角色的权限分配
     * @param roleId 角色ID
     * @param permissionIds 权限ID列表
     * @return 更新结果
     */
    @PutMapping("/{roleId}/permissions")
    public ResponseEntity<Map<String, Object>> updateRolePermissions(
            @PathVariable Long roleId,
            @RequestBody List<Long> permissionIds) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = roleService.updateRolePermissions(roleId, permissionIds);
            if (success) {
                result.put("success", true);
                result.put("message", "更新角色权限成功");
            } else {
                result.put("success", false);
                result.put("message", "更新角色权限失败");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新角色权限失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    /**
     * 删除指定角色及其权限关联
     * @param roleId 角色ID
     * @return 删除结果
     */
    @DeleteMapping("/{roleId}")
    public ResponseEntity<Map<String, Object>> deleteRole(@PathVariable Long roleId) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = roleService.deleteRoleWithPermissions(roleId);
            if (success) {
                result.put("success", true);
                result.put("message", "删除角色成功");
            } else {
                result.put("success", false);
                result.put("message", "删除角色失败");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除角色失败：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }

    @GetMapping("/getRoleOptions")
    public ResponseEntity<?> getRoleOptions() {
        List<Role> list = roleService.list();
        return ResponseEntity.ok(list);
    }
}